package com.googlecode.h0v3rk4rt.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * This class is used to test the one-way lag between
 * two computers over a network.
 * @author Nilay Kumar
 *
 */
public class LagTestServer {

	public static void main(String[] args) {
		try {
			System.out.print("Would you like to use TCP or UDP?");
			int option = System.in.read();
			if(option == 116) // TCP
				tcpTest();
			else // UDP
				udpTest();
		} catch (SocketException e) {
			GameError.showErrorDialog(e);
		} catch (IOException e) {
			GameError.showErrorDialog(e);
		} catch (ClassNotFoundException e) {
			GameError.showErrorDialog(e);
		}
	}
	
	private static void tcpTest() throws IOException, ClassNotFoundException {
		System.out.println("Starting TCP server...");
		ServerSocket server = new ServerSocket(40313);
		System.out.println("TCP server online. Waiting for connections...");
		Socket connection = server.accept();
		long input = -1;
		while(input == -1)
			input = (Long) new ObjectInputStream(connection.getInputStream()).readObject();
		long lag = System.currentTimeMillis() - input;
		System.out.println("Lag measured: " + System.currentTimeMillis() + " - " + input + " = " + lag + " ms.");
	}
	
	private static void udpTest() throws IOException {
		System.out.println("Starting UDP server...");
		DatagramSocket server = new DatagramSocket(40314);
		System.out.println("UDP server online. Waiting for packets...");
		byte[] buf = new byte[256];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		server.receive(packet);
		String received = new String(packet.getData(), 0, packet.getLength());
		long input = Long.parseLong(received);
		long lag = System.currentTimeMillis() - input;
		System.out.println("Lag measured: " + System.currentTimeMillis() + " - " + input + " = " + lag + " ms.");
		
	}

}
